
package geym.conc.ch3.pool;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class ExtThreadPool {
    public static class MyTask implements Runnable {
        public String name;

        public MyTask(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            System.out.println("正在执行" + ":Thread ID:" + Thread.currentThread().getId()
                    + ",Task Name=" + name);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static class MyTaskCallable implements Callable<String> {
        public String name;

        public MyTaskCallable(String name) {
            this.name = name;
        }

        @Override
        public String call() {
            System.out.println("正在执行" + ":Thread ID:" + Thread.currentThread().getId()
                    + ",Task Name=" + name);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "";
        }
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {

        ExecutorService es = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>()) {
            @Override
            protected void beforeExecute(Thread t, Runnable r) {
                if(r instanceof MyTask){
                    System.out.println("准备执行：" + ((MyTask) r).name);
                }else {
                    System.out.println("准备执行：" + t.getName());
                }
            }

            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                if(r instanceof MyTask){
                    System.out.println("执行完成：" + ((MyTask) r).name);
                }else {
                    System.out.println("执行完成：" + Thread.currentThread().getName());
                }
            }

            @Override
            protected void terminated() {
                System.out.println("线程池退出");
            }

        };
        List<Future> futureList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
//            MyTask task = new MyTask("TASK-GEYM-" + i);
//            es.execute(task);
            MyTaskCallable task = new MyTaskCallable("TASK-GEYM-" + i);
            futureList.add(es.submit(task));
            Thread.sleep(10);
        }
//        for (Future future : futureList) {
//            future.get();
//        }
        es.shutdown();
    }
}
